/*
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.bezrabotnih.cabinet.client.activity;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

import net.bezrabotnih.cabinet.client.activity.ProviderJobsActivity.ParentActivity;
import net.bezrabotnih.cabinet.client.app.DesktopApplication;
import net.bezrabotnih.cabinet.client.place.EditJobPlace;
import net.bezrabotnih.cabinet.client.place.MenuItemPlace;
import net.bezrabotnih.cabinet.client.place.ProviderJobsPlace;
import net.bezrabotnih.cabinet.client.request.CabinetCommentRequest;
import net.bezrabotnih.cabinet.client.request.CabinetJobRequest;
import net.bezrabotnih.cabinet.client.request.CabinetRequestFactory;
import net.bezrabotnih.cabinet.client.request.CabinetUserAccountRequest;
import net.bezrabotnih.cabinet.client.ui.ProviderJobsView;
import net.bezrabotnih.cabinet.client.ui.ProviderJobBlockView;
import net.bezrabotnih.cabinet.client.ui.ProviderJobsViewImpl;
import net.bezrabotnih.client.managed.request.ApplicationProxy;
import net.bezrabotnih.client.managed.request.CommentProxy;
import net.bezrabotnih.client.managed.request.JobProxy;
import net.bezrabotnih.client.managed.request.JobRequest;
import net.bezrabotnih.client.managed.request.JobTypeProxy;
import net.bezrabotnih.client.managed.request.UserAccountProxy;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.requestfactory.shared.Receiver;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

/**
 * Activities are started and stopped by an ActivityManager associated with a container Widget.
 */
public class ProviderJobsActivity extends AbstractActivity implements ProviderJobsView.Presenter, ProviderJobBlockView.Presenter {

	
	private static final Logger log = Logger.getLogger(ProviderJobsActivity.class.getName());
	/**
	 * Sample property.
	 */
	private String name;

	private MenuItemPlace place;
	private CabinetRequestFactory requestFactory;
	private PlaceController placeController;
	
	private ProviderJobsView view;
	
    private UserAccountProxy currentUserAccountProxy;
	
	private List<JobProxy> jobProxies;

	private ParentActivity parentActivity; 
	
	public ProviderJobsActivity(MenuItemPlace place,CabinetRequestFactory requestFactory,PlaceController placeController) {
		this.place=place;
		this.requestFactory=requestFactory;
		this.placeController=placeController;
		
		
	}

	@SuppressWarnings("deprecation")
	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		this.view = new ProviderJobsViewImpl();
		view.setPresenter(this);
		containerWidget.setWidget(view.asWidget());
		
		requestFactory.cabinetUserAccountRequest().currentUserAccount().fire(new Receiver<UserAccountProxy>() {
			
			@Override
			public void onSuccess(final UserAccountProxy userAccountProxy) {
				currentUserAccountProxy=userAccountProxy;
				populateJobs();
				
				
				
			}
		});
		
	}

	@Override
	public String mayStop() {
		return null;
	}

	/**
	 * @see ProviderJobsView.Presenter#goTo(Place)
	 */
	public void goTo(Place place) {
		// TODO
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void winnerCancelClicked(String jobId) {
		final JobProxy originalProxy=findJobProxyById(jobId);
		if (originalProxy!=null){
			if (originalProxy.getWinnerId()!=null){
			JobRequest request=requestFactory.cabinetJobRequest();
			final JobProxy jobProxy=request.edit(originalProxy);
			jobProxy.setWinnerId(null);
			request.persist().using(jobProxy).fire(new Receiver<Void>() {

				@Override
				public void onSuccess(Void response) {
					jobProxies.remove(originalProxy);
					jobProxies.add(jobProxy);
					showApplicantsView(jobProxy);
					if (parentActivity!=null) parentActivity.jobsRefreshed();
				}
			});
			}
			
			
		}
		
	}

	@SuppressWarnings("deprecation")
	@Override
	public void confirm(String jobId,String applicantId,final String name) {
		final JobProxy originalProxy=findJobProxyById(jobId);
		if (originalProxy!=null){
			CabinetJobRequest request=requestFactory.cabinetJobRequest();
			final JobProxy jobProxy=request.edit(originalProxy);
			jobProxy.setWinnerId(applicantId);
			request.persist().using(jobProxy).fire(new Receiver<Void>() {

				@Override
				public void onSuccess(Void response) {
					jobProxies.remove(originalProxy);
					jobProxies.add(jobProxy);
					view.setWinner(jobProxy.getId(), null, name);
					if (parentActivity!=null) parentActivity.jobsRefreshed();
				}
			});
			
			
		}
		
	}

	@SuppressWarnings("deprecation")
	@Override
	public void populateApplicants(String jobId) {
		final JobProxy jobProxy=findJobProxyById(jobId);
		if (jobProxy!=null){
			if (jobProxy.getWinnerId()!=null){
				showWinnerView(jobProxy);
			}else{
				showApplicantsView(jobProxy);
			}
			
			
			
		}
		
	}
	
	@SuppressWarnings("deprecation")
	private void showWinnerView(final JobProxy jobProxy){

		
		requestFactory.cabinetUserAccountRequest().findUserAccount(jobProxy.getWinnerId()).fire(new Receiver<UserAccountProxy>() {

			@Override
			public void onSuccess(UserAccountProxy userAccountProxy) {
			view.setWinner(jobProxy.getId(),null,userAccountProxy.getName());
			}
		});
	
	}
	
	@SuppressWarnings("deprecation")
	private void showApplicantsView(final JobProxy jobProxy){
		
		
		
		requestFactory.cabinetApplicationRequest().findApplicationsByJobId(jobProxy.getId()).with("userAccount").fire(new Receiver<List<ApplicationProxy>>() {

			@Override
			public void onSuccess(List<ApplicationProxy> applicationProxies) {

				view.clearApplicantsListPanel();
				if (applicationProxies!=null){
					for (ApplicationProxy applicationProxy:applicationProxies){
						UserAccountProxy userAccountProxy=applicationProxy.getUserAccount();
						view.addAddApplicant(jobProxy.getId(),userAccountProxy.getId(),userAccountProxy.getThumbnailUrl(),userAccountProxy.getName());
					}
					if (applicationProxies.size()>=0){

						view.showApplicantsView();

					}
				}
			
				
				
			}
		});
	
		
	}
	
	public void setParentActivity(ParentActivity parentActivity){
		
		this.parentActivity=parentActivity;
	}
	
	
	private JobProxy findJobProxyById(String id){
		if (jobProxies!=null)
			for (JobProxy proxy:jobProxies){
				if (id.equals(proxy.getId())) return proxy;
			}
			return null;
		}
	
	@SuppressWarnings("deprecation")
	public void populateJobs() {
		
		if (currentUserAccountProxy!=null){
			
			view.clearJobsView();
			
		requestFactory.cabinetJobRequest().findJobsByProviderId(currentUserAccountProxy.getId()).with("jobType").fire(new Receiver<List<JobProxy>>() {
		
		
		@Override
		public void onSuccess(final List<JobProxy> jobProxies) {
			
			ProviderJobsActivity.this.jobProxies=jobProxies;
			
			view.setJobsTableData(jobProxies);
			
			
//			requestFactory.cabinetJobTypeRequest().findAllJobTypes().fire(new Receiver<List<JobTypeProxy>>() {
//
//				@Override
//				public void onSuccess(List<JobTypeProxy> jobTypeProxies) {
//					HashMap<String, String> jobTypesMap=new HashMap<String, String>();
//					for(JobTypeProxy jobTypeProxy:jobTypeProxies){
//						jobTypesMap.put(jobTypeProxy.getId(), jobTypeProxy.getName());
//					}
//					
//					int proxyCount=ProviderJobsActivity.this.jobProxies.size();
//					for (int i=0;i<proxyCount;i++){
//						JobProxy jobProxy=jobProxies.get(proxyCount-1-i);
//						
//						String jobStatusStr=jobProxy.getStatus()==0?"новая":"выполнена";
//						
//						view.addJobBlock(ProviderJobsActivity.this, 
//								jobProxy.getId(),
//								jobProxy.getName(),
//								jobTypesMap.get(jobProxy.getJobTypeId()),
//								jobStatusStr,
//								jobProxy.getIsHourly(),
//								jobProxy.getStartDate(),
//								jobProxy.getDeadLine(),
//								jobProxy.getPrice(),
//								jobProxy.getDescription());
//				
//					}
//					
//					
//				}
//			});
			
			
			
		}
		
		});
	
		}
	}
	public interface ParentActivity{
		
		void jobsRefreshed();
		
	}
	@Override
	public void jobEditClicked(String jobId) {
		placeController.goTo(new EditJobPlace(jobId));
		
	}

	@SuppressWarnings("deprecation")
	@Override
	public void showJobDetails(JobProxy jobProxy) {
		final String jobId=jobProxy.getId();
		final String jobName=jobProxy.getName();
		final String jobStatus=jobProxy.getStatus()==0?"новая":"";
		final boolean isHourly=jobProxy.getIsHourly();
		final Date startDate=jobProxy.getStartDate();
		final Date deadline=jobProxy.getDeadLine();
		final Integer price=jobProxy.getPrice();
		final String description=jobProxy.getDescription();
		
		Receiver<? super JobTypeProxy> receiver=new Receiver<JobTypeProxy>() {
			@Override
			public void onSuccess(JobTypeProxy jobTypeProxy) {
				String  jobType=jobTypeProxy.getName();
				view.setJobDetailsView(new ProviderJobBlockView(ProviderJobsActivity.this, jobId, jobName, jobType, jobStatus, isHourly, startDate, deadline, price, description));
				
			}
		};
		
		
		requestFactory.jobTypeRequest().findJobType(jobProxy.getJobTypeId()).fire(receiver);
		

	}

	@SuppressWarnings("deprecation")
	@Override
	public void populateComments(final String jobId) {
		 log.info("populate comments");
			requestFactory.cabinetCommentRequest().findCommentsByJobId(jobId).with("userAccount").fire(new Receiver<List<CommentProxy>>() {
				@Override
				public void onSuccess(List<CommentProxy> comments) {
					log.info("comments found");
					if (comments!=null){
						for (CommentProxy commentProxy:comments){
							UserAccountProxy userAccountProxy=commentProxy.getUserAccount();
							log.info("comment to populat:"+commentProxy.getId()+"  userAccountId:"+commentProxy.getUserAccountId() );
							if (userAccountProxy!=null){
								view.addComment(userAccountProxy.getThumbnailUrl(), userAccountProxy.getName(), commentProxy.getText());
							    log.info("comment populated");
							}
							
						}
					}

				}
			});
		
		
	}
	
	@SuppressWarnings("deprecation")
	public void submitComment(final String jobId,final String text){
		
		CabinetCommentRequest request=requestFactory.cabinetCommentRequest();
		CommentProxy commentProxy=request.create(CommentProxy.class);
		commentProxy.setText(text);
		commentProxy.setJobId(jobId);
		commentProxy.setUserAccountId(currentUserAccountProxy.getId());
		log.info("comment to persist:userAccountId="+commentProxy.getUserAccountId());
		final String thumbnailUrl=currentUserAccountProxy.getThumbnailUrl();
		request.persist().using(commentProxy).fire(new Receiver<Void>() {
			@Override
			public void onSuccess(Void response) {
				log.info("comment persisted");
				view.addComment(thumbnailUrl, currentUserAccountProxy.getName(), text);
				
			}
		});
		
		
	}
	
	
}
